package io.renren.modules.sp.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.annotation.SeasonFilter;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sp.dao.TAreaDao;
import io.renren.modules.sp.dto.SpMatchDTO;
import io.renren.modules.sp.entity.SpMatchEntity;
import io.renren.modules.sp.entity.TAreaEntity;
import io.renren.modules.sp.excel.SpLeaderExcel;
import io.renren.modules.sp.excel.SpMatchExcel;
import io.renren.modules.sp.service.SpMatchService;
import io.renren.modules.sp.service.TAreaService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysRoleUserService;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
* 赛事
*
* @author whc 15953295779@126.com
* @since 3.0 2023-04-21
*/
@RestController
@RequestMapping("sp/spmatch")
@Api(tags="赛事")
public class SpMatchController {
    @Autowired
    private SpMatchService spMatchService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TAreaService tAreaService;
    @Autowired
    private SysRoleUserService sysRoleUserService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    //@RequiresPermissions("sp:spmatch:page")
    public Result<PageData<SpMatchDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        //获取当前登录用户
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        if(user.getDeptId()!=null) {
            // 判断管理员的角色
            String userType = sysUserService.getSysUserType();
            //如果是赛项管理员
            if ("2".equals(userType)) {
                params.put("itemAdminId", user.getId());
            }
            //如果是赛事管理员
            if ("1".equals(userType) || "3".equals(userType) || "4".equals(userType)) {
                params.put("adminId", user.getId());
            }
            // 打分员
            if ("5".equals(userType)) {
                if(user.getMatchId()!=null) {
                    params.put("id", user.getMatchId());
                }
            }
        }
        if(params.get("beginSignup")!=null&&params.get("beginSignup").toString().length()==10){
            params.put("beginSignup", DateUtils.parse(params.get("beginSignup").toString(),DateUtils.DATE_FORMAT_YEAR_MONTH));
        }else{
            params.remove("beginSignup");
        }
        if(params.get("endSignup")!=null&&params.get("endSignup").toString().length()==10){
            params.put("endSignup", DateUtils.parse(params.get("endSignup").toString()+" 23:59:59",DateUtils.DATE_TIME_PATTERN));
        }else{
            params.remove("endSignup");
        }
        PageData<SpMatchDTO> page = spMatchService.queryPage(params);
        // 循环设置母赛事
        for (SpMatchDTO spMatchDTO : page.getList()) {
            if (spMatchDTO.getMatchParentId() != null) {
                SpMatchEntity parent = spMatchService.selectById(spMatchDTO.getMatchParentId());
                if(parent != null){
                    spMatchDTO.setMatchParentName(parent.getMatchName());
                }
            }
            //设置省
            if(spMatchDTO.getProvince()!=null){
                TAreaEntity tAreaEntity = tAreaService.getByCode(spMatchDTO.getProvince());
                if(tAreaEntity!=null){
                    spMatchDTO.setProvinceName(tAreaEntity.getName());
                }
            }
            //设置市
            if(spMatchDTO.getCity()!=null){
                TAreaEntity tAreaEntity = tAreaService.getByCode(spMatchDTO.getCity());
                if(tAreaEntity!=null){
                    spMatchDTO.setCity(tAreaEntity.getName());
                }
            }
            // 设置管理员
            if(spMatchDTO.getAdminId()!=null){
                SysUserEntity sysUserEntity = sysUserService.selectById(spMatchDTO.getAdminId());
                if(sysUserEntity!=null){
                    spMatchDTO.setAdminName(sysUserEntity.getRealName());
                }
            }
        }
        return new Result<PageData<SpMatchDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("sp:spmatch:info")
    public Result<SpMatchDTO> get(@PathVariable("id") Long id){


        SpMatchDTO data = spMatchService.get(id);
        if(data.getAdminId()!=null){
            SysUserEntity sysUserEntity = sysUserService.selectById(data.getAdminId());
            if(sysUserEntity!=null){
                data.setAdminName(sysUserEntity.getUsername());
            }
        }
        return new Result<SpMatchDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sp:spmatch:save")
    public Result save(@RequestBody SpMatchDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        if(StringUtils.isEmpty(dto.getProvince())){
            dto.setProvince(null);
        }
        if(StringUtils.isEmpty(dto.getCity())){
            dto.setCity(null);
        }
        dto.setEndDate(DateUtils.parse(DateUtils.format(dto.getEndDate())+" 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        dto.setEndSignup(DateUtils.parse(DateUtils.format(dto.getEndSignup())+" 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        spMatchService.save(dto);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sp:spmatch:update")
    public Result update(@RequestBody SpMatchDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        if(StringUtils.isEmpty(dto.getProvince())){
            dto.setProvince(null);
        }
        if(StringUtils.isEmpty(dto.getCity())){
            dto.setCity(null);
        }
        dto.setEndDate(DateUtils.parse(DateUtils.format(dto.getEndDate())+" 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        dto.setEndSignup(DateUtils.parse(DateUtils.format(dto.getEndSignup())+" 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        spMatchService.update(dto);
        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sp:spmatch:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        spMatchService.delete(ids);
        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sp:spmatch:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SpMatchDTO> list = spMatchService.list(params);
        ExcelUtils.exportExcelToTarget(response, null, "赛事", list, SpMatchExcel.class);
    }

    @GetMapping("list")
    @SeasonFilter
    public Result<List<SpMatchDTO>> list(@ApiIgnore @RequestParam Map<String, Object> params){
        //获取当前登录用户
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        if(user.getDeptId()!=null) {
            String userType = sysUserService.getSysUserType();
            //如果是赛项管理员
            if ("2".equals(userType)) {
                params.put("itemAdminId", user.getId());
            }
            //如果是赛事管理员
            if ("1".equals(userType) || "3".equals(userType) || "4".equals(userType)) {
                params.put("adminId", user.getId());
            }
        }
        List<SpMatchDTO> page = spMatchService.list(params);
        return new Result<List<SpMatchDTO>>().ok(page);
    }

    @GetMapping("generateTicketNo")
    @ApiOperation("生成比赛证件编号")
    @LogOperation("生成比赛证件编号")
    @RequiresPermissions("sp:spmatch:genTick")
    public Result generateTicketNo(@RequestParam Long matchId){
        spMatchService.generateTicketNo(matchId);
        return new Result();
    }

    /**
     * 下载领队照片
     * @param params
     * @return
     */
    @LogOperation("下载领队照片")
    @GetMapping("/downloadLeaderHeaderFile")
    @RequiresPermissions("sp:spmatch4:leaderPic")
    public Result<String> downloadLeaderHeaderFile(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        return spMatchService.downloadLeaderHeaderFile(params,response);
    }

    /**
     * 导出领队表单
     * @param params
     * @return
     */
    @GetMapping("exportLeaderForm")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sp:spmatch4:leaderForm")
    public void exportLeaderForm(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> list = spMatchService.exportLeaderForm(params);
        List<SpLeaderExcel> excelList = new ArrayList<>();
        SpLeaderExcel excel = null;
        for(Map<String, Object> map : list) {
            excel = new SpLeaderExcel();
            excel.setId(((Long) map.get("id")).intValue());
            excel.setTeamName((String) map.get("teamName"));
            excel.setCompany((String) map.get("company"));
            excel.setLeader((String) map.get("leader"));
            excel.setPhone((String) map.get("phone"));
            excel.setLeaderPhone((String) map.get("leaderPhone"));
            excel.setTeamCode((String) map.get("teamCode"));
            excel.setItemName((String) map.get("itemName"));
            excel.setStudentNum(((Long) map.get("studentNum")).intValue());
            excel.setProvince((String) map.get("province"));
            excel.setCity((String) map.get("city"));
            String realName = (String) map.get("realName");
            // 顿号分割姓名
            if (realName != null) {
                String[] leaders = realName.split("、");
                for (int i = 0; i < leaders.length; i++) {
                    if (i == 0) {
                        excel.setLeader1(leaders[i]);
                    }
                    if (i == 1) {
                        excel.setLeader2(leaders[i]);
                    }
                    if (i == 2) {
                        excel.setLeader3(leaders[i]);
                    }
                    if (i == 3) {
                        excel.setLeader4(leaders[i]);
                    }
                }
            }
            excelList.add(excel);
        }
        ExcelUtils.exportExcelToTarget(response, null, "领队表单", excelList, SpLeaderExcel.class);
    }

}
